const Router = require('koa-router');
const mysql = require('mysql2/promise');
const bodyParser = require('koa-bodyparser');
const { koaBody } = require('koa-body');
const fs = require('fs');
const path = require('path');

const router = new Router();
router.use(bodyParser());

const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'student',
};

// 创建上传目录
const UPLOAD_DIR = path.join(__dirname, 'uploads');
const TEMP_DIR = path.join(UPLOAD_DIR, 'temp');
if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR);
if (!fs.existsSync(TEMP_DIR)) fs.mkdirSync(TEMP_DIR);

// 将文件名转换为安全名称
function safeName(name) {
  return name.replace(/[ #?&%/:<>*|"\\]/g, '_');
}

/**
 * 📌 接收分片保存
 */
router.post('/upload-files', koaBody({ multipart: true }), async (ctx) => {
  try {
    const { files, body } = ctx.request;
    const chunk = files?.file;
    let { index, total, filename } = body;

    if (!chunk) {
      ctx.body = { code: 400, message: "未找到文件" };
      return;
    }

    // 保留原始文件名
    const ext = path.extname(filename);              // 
    const basename = path.basename(filename, ext);   // 分片
    const safeBase = safeName(basename);             // 安全目录名

    // 每个文件创建独立目录临时存储分片
    const fileTempDir = path.join(TEMP_DIR, safeBase);
    if (!fs.existsSync(fileTempDir)) fs.mkdirSync(fileTempDir);

    // 分片保存路径
    const chunkPath = path.join(fileTempDir, `${index}`);

    // 保存分片
    const reader = fs.createReadStream(chunk.filepath);
    const writer = fs.createWriteStream(chunkPath);
    reader.pipe(writer);

    ctx.body = {
      code: 200,
      message: "分片上传成功",
      data: { index, total }
    };

  } catch (err) {
    console.error(err);
    ctx.status = 500;
    ctx.body = { code: 500, message: "分片上传失败" };
  }
});


/**
 * 📌 合并分片接口
 */
router.post("/mergeFile", async (ctx) => {
  try {
    let { filename } = ctx.request.body;

    const ext = path.extname(filename);
    const basename = path.basename(filename, ext);
    const safeBase = safeName(basename);

    const fileTempDir = path.join(TEMP_DIR, safeBase);
    const finalFilePath = path.join(UPLOAD_DIR, filename);

    console.log("🔧 开始合并分片目录：", fileTempDir);

    // 获取分片列表（从服务器读取）
    let chunks = fs.readdirSync(fileTempDir);

    // 排序（按数字）
    chunks.sort((a, b) => Number(a) - Number(b));

    console.log("📌 分片排序结果: ", chunks);

    const writeStream = fs.createWriteStream(finalFilePath);

    for (let chunkName of chunks) {
      const chunkPath = path.join(fileTempDir, chunkName);
      console.log("🔨 合并分片: ", chunkPath);

      const data = fs.readFileSync(chunkPath);
      writeStream.write(data);
    }

    writeStream.end();

    ctx.body = {
      code: 200,
      message: "文件合并完成",
      data: { filename },
    };
  } catch (err) {
    console.error("合并失败：", err);
    ctx.status = 500;
    ctx.body = { code: 500, message: "合并失败" };
  }
});

module.exports = router;
